package com.china.zhuoyue.ui.ext

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.view.View
import android.widget.EditText
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.china.zhuoyue.ui.AppCore
import com.china.zhuoyue.ui.utils.Utils

val Int.dp get() = (this * AppCore.app.resources.displayMetrics.density + 0.5f).toInt()
val Int.drawable get() = ContextCompat.getDrawable(AppCore.app, this)
val Boolean.toInt get() = if (this) 1 else 0
fun dp2px(dpValue: Int) = (dpValue * AppCore.app.resources.displayMetrics.density + 0.5f).toInt()
fun toastMessageLong(strIdes: Int) = Utils.toastMessageLong(AppCore.app, AppCore.app.getString(strIdes))
fun toastMessageLong(str: String?) = Utils.toastMessageLong(AppCore.app, str)
fun getString(strIdes: Int) = AppCore.app.getString(strIdes)
fun getString(strIdes: Int, vararg formatArgs: Any) = AppCore.app.getString(strIdes, *formatArgs)
fun bindViewClick(listener: View.OnClickListener, vararg views: View) {
    for (it in views) {
        it.setOnClickListener(listener)
    }
}

fun java.io.Closeable.tryClose() {
    try {
        close()
    } catch (e: Exception) {

    }
}

val EditText.value get() = text.toString()
val TextView.value get() = text.toString()

inline fun <reified T : Activity> Activity.startActivityForResultExt(requestCode: Int, noinline intent: (Intent.() -> Unit)? = null) {
    startActivityForResult(buildIntent<T>(intent), requestCode)
}

inline fun <reified T : Activity> Fragment.startActivityForResultExt(requestCode: Int, noinline intent: (Intent.() -> Unit)? = null) {
    startActivityForResult(requireContext().buildIntent<T>(intent), requestCode)
}

inline fun <reified T : Activity> Activity.startActivityExt(noinline intent: (Intent.() -> Unit)? = null) {
    startActivity(buildIntent<T>(intent))
}

inline fun <reified T : Activity> Fragment.startActivityExt(noinline intent: (Intent.() -> Unit)? = null) {
    startActivity(requireContext().buildIntent<T>(intent))
}

inline fun <reified T : Activity> Context.startActivityExt(noinline intent: (Intent.() -> Unit)? = null) {
    startActivity(buildIntent<T>(intent))
}

inline fun <reified T : Context> Context.buildIntent(noinline initIntent: (Intent.() -> Unit)? = null): Intent {
    val intent = Intent(this, T::class.java)
    if (initIntent != null) {
        intent.apply(initIntent)
    }
    return intent
}